/**
 * Copyright:Copyright(c)2014-2017
 * Company:厦门市易致达物联网科技有限公司
 * @version 1.0
 */
package shop.controller.manage.product;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import shop.core.BaseController;
import shop.core.common.bean.JSONResult;
import shop.services.manage.nature.NatureService;
import shop.services.manage.nature.bean.Nature;
import shop.services.manage.product.ProductService;
import shop.services.manage.product.bean.Product;
import shop.services.manage.spec.SpecService;
import shop.services.manage.spec.bean.Spec;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**   
 * @类名称：ProductAction      
 * @创建人：Ltz   
 * @创建时间：2017-09-20 下午15:50:43      
 * @版本号：1.0
 * @描述：     
 */
@Controller
@RequestMapping("/manage/product/")
public class ProductAction extends BaseController<Product> {
    private static final Logger logger = LoggerFactory.getLogger(ProductAction.class);
    @Autowired
    private ProductService productService;

    @Autowired
    private SpecService specService;

    @Autowired
    private NatureService natureService;

    private static final String page_toList = "/manage/product/productList";
    private static final String page_toAdd = "/manage/product/productAdd";
    private static final String page_toEdit = "/manage/product/productEdit";
    public ProductService getService() {
        return productService;
    }

    private ProductAction(){
        super.page_toList = page_toList;
        super.page_toAdd = page_toAdd;
        super.page_toEdit = page_toEdit;
    }

    /**
     * 跳转编辑页面时查询商品
     */
    @Override
    public String toEdit(@ModelAttribute("e")Product e, ModelMap model) throws Exception {
        if(StringUtils.isBlank(e.getId())){
            throw new NullPointerException("商品ID不能为空！");
        }
        e = getService().selectAllById(e.getId());
        if(e==null || StringUtils.isBlank(e.getId())){
            throw new NullPointerException("根据商品ID查询不到指定的商品！");
        }
        model.addAttribute("e", e);
        return page_toEdit;
    }


    /**
     * 商品上下架--批量更改
     *
     * @param ids 改变状态的商品ID集合
     * @return
     */
    @RequestMapping(value = "changeStatus",method = RequestMethod.POST)
    @ResponseBody
    public JSONResult changeStatus(HttpServletRequest request, @RequestParam(value = "idArr[]") String[] ids){
        JSONResult rs =new JSONResult();
        String changeType=request.getParameter("type");
        if(changeType.equals("0")){
            productService.updateProductStatus(ids,1);
        } else if(changeType.equals("1")){
            productService.updateProductStatus(ids,0);
        }
        rs.setSuccess(true);
        return rs;
    }

    /**
     * 商品上下架--批量更改
     *
     * @param id 改变状态的商品ID
     * @return
     */
    @RequestMapping(value = "changeOneStatus",method = RequestMethod.POST)
    @ResponseBody
    public JSONResult changeOneStatus(HttpServletRequest request, @RequestParam(value = "id") String id){
        JSONResult rs =new JSONResult();
        String	changeType=request.getParameter("type");
        if(changeType.equals("0")){
            productService.updateOneProductStatus(id, 1);
        } else if(changeType.equals("1")) {
            productService.updateOneProductStatus(id, 0);
        }
        rs.setSuccess(true);
        return rs;
        }

        /**
        * 根据ID删除单个商品信息
         *
         *  @return jsonResult
         * @throws Exception
        * */
        @RequestMapping(value = "deleteByIdJson", method = RequestMethod.POST)
        @ResponseBody
        public JSONResult deleteByIdJson(@RequestParam(value = "id") int id) throws Exception {
            JSONResult jsonResult = new JSONResult();
            getService().deleteById(id);
            specService.deleteByPID(id);
            natureService.deleteByPID(id);
            jsonResult.setMessage("success");
            return jsonResult;
        }

    /**
     *  添加商品--包括规格
     */
    @RequestMapping(value = "insertAllJson",method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertAllJson(HttpServletRequest request, @ModelAttribute("e") Product e) throws Exception {
        int productID =getService().insert(e);
        //强制转化为string类型
        String[] specCombinations=e.getSpecCombination().split(";");
        String[] specStocks=e.getSpecStock().split(";");
        String[] specNowPrices=e.getSpecNowPrice().split(";");
        String[] specpurchaseprices=e.getSpecPurchasePrice().split(";");
        //逐个添加商品规格
        for(int i=0;i<specCombinations.length;i++){
            Spec spec = new Spec();
            spec.setProductID(String.valueOf(productID));
            spec.setSpecCombination(specCombinations[i]);
            spec.setSpecStock(Integer.parseInt(specStocks[i]));
            spec.setSpecNowPrice(new BigDecimal(specNowPrices[i]));
            spec.setSpecPurchasePrice(new BigDecimal(specpurchaseprices[i]));
            specService.insert(spec);
        }
        //强制转化为string类型
        String[] natureName=e.getNatureName().split(";");
        String[] natureValue=e.getNatureValue().split(";");
        //逐个添加商品规格
        for(int i=0;i<natureName.length;i++){
            Nature nature = new Nature();
            nature.setProductID(String.valueOf(productID));
            nature.setName(natureName[i]);
            nature.setNatureValue(natureValue[i]);
            natureService.insert(nature);
        }
        return new JSONResult(productID,productID>0?true:false);
    }

    /**
    * 更新商品信息--主要为了更新商品的上下架状态
    * */
    @RequestMapping(value = "updateProductJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateProductJson(HttpServletRequest request, @ModelAttribute("e") Product e) throws Exception {
        JSONResult jsonResult = new JSONResult();
        e.setStatus(0);
        getService().update(e);
        return jsonResult;
    }

    /**
     * 批量删除商品--包含删除规格和参数
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "deletesProductJson", method = RequestMethod.POST)
    @ResponseBody
    public String deletesProductJson(HttpServletRequest request, @RequestParam(value = "ids[]") String[] ids, @ModelAttribute("e") Product e, RedirectAttributes flushAttrs) throws Exception {
        getService().deletes(ids);
        specService.deletesByPID(ids);
        natureService.deletesByPID(ids);
        return "success";
    }

    /**
     * 查找所有的商品
     * @return
     */
    @RequestMapping(value = "getAllProduct",method = RequestMethod.GET)
    @ResponseBody
    public JSONResult getAllProduct(){
        JSONResult rs=new JSONResult();
        Product product=new Product();
        List<Product> productList=getService().selectList(product);
        rs.setData(productList);
        rs.setSuccess(true);
        return rs;
    }
}
